﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Geometry = Esri.ArcGISRuntime.Geometry.Geometry;

namespace classTest
{
    /// <summary>
    /// SiteSelectionWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SiteSelectionWindow : Window
    {
        private MapView MyMapView;

        private List<string> sDistance = new List<string>();
        private List<FeatureLayer> sFeatureLayer = new List<FeatureLayer>();
        private List<string> sType = new List<string>();
        private GraphicsOverlay _siteGraphicsOverlay;

        public SiteSelectionWindow(MapView mapView, GraphicsOverlay siteGraphicsOverlay)
        {
            InitializeComponent();
            MyMapView = mapView;
            _siteGraphicsOverlay = siteGraphicsOverlay;

            Initializing();
        }

        // 初始化
        private void Initializing()
        {
            LayerCollection layers =MyMapView.Map.OperationalLayers;
            for(int i = layers.Count - 1; i >= 0; i--)
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = layers[i].Name;
                cbi.DataContext = layers[i];
                comboBox.Items.Add(cbi);
            }
        }

        // 添加
        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Convert.ToDouble(textBox.Text);
            }
            catch
            {
                MessageBox.Show("添加失败");
            }
            if (comboBox.SelectedIndex == -1) return;


            FeatureLayer featureLayer = (comboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;

            ListBoxItem lbi = new ListBoxItem();
            string type = "";
            if (inRadioButton.IsChecked == true)
            {
                type = "之内";
            }
            else{
                type = "之外";
            }

            sDistance.Add(textBox.Text);
            sFeatureLayer.Add(featureLayer);
            sType.Add(type);

            lbi.Content = $"距离图层 {featureLayer.Name} {textBox.Text} 米 {type}";

            listBox.Items.Add(lbi);

        }

        // 修改
        private void alterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Convert.ToDouble(textBox.Text);
            }
            catch
            {
                MessageBox.Show("修改失败");
            }
            if (comboBox.SelectedIndex == -1) return;


            FeatureLayer featureLayer = (comboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;

            ListBoxItem lbi = new ListBoxItem();
            int index = listBox.SelectedIndex;
            string type = "";
            if (inRadioButton.IsChecked == true)
            {
                type = "之内";
            }
            else
            {
                type = "之外";
            }

            sDistance[index] = textBox.Text;
            sFeatureLayer[index] = featureLayer;
            sType[index] = type;

            lbi.Content = $"距离图层 {featureLayer.Name} {textBox.Text} 米 {type}";

            listBox.Items.RemoveAt(index);
            listBox.Items.Insert(index, lbi);

            alterButton.Visibility = Visibility.Hidden;
            deleteButton.Visibility = Visibility.Hidden;
        }

        // 选择时，还原相关配置
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox.SelectedIndex == -1) return;
            alterButton.Visibility = Visibility.Visible;
            deleteButton.Visibility = Visibility.Visible;
            int index = listBox.SelectedIndex;
            textBox.Text = sDistance[index];
            if (sType[index] == "之内")
            {
                inRadioButton.IsChecked = true;
            }
            else
            {
                outRadioButton.IsChecked = true;
            }
            LayerCollection layers = MyMapView.Map.OperationalLayers;
            for (int i = layers.Count - 1; i >= 0; i--)
            {
                if (layers[i].Name == sFeatureLayer[index].Name)
                {
                    comboBox.SelectedIndex = layers.Count - i - 1;
                    break;
                }
            }
        }

        // 删除
        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            alterButton.Visibility = Visibility.Hidden;
            deleteButton.Visibility = Visibility.Hidden;
            int index = listBox.SelectedIndex;
            sDistance.RemoveAt(index);
            sFeatureLayer.RemoveAt(index);
            sType.RemoveAt(index);
            listBox.Items.RemoveAt(index);
        }

        // 开始运行
        private async void execButton_Click(object sender, RoutedEventArgs e)
        {
            List<Geometry> union = new List<Geometry>();
            List<Geometry> cut = new List<Geometry>();
            for (int i = 0; i < sType.Count; i++)
            {
                if (sType[i] == "之内")
                {
                    QueryParameters qParams = new QueryParameters();//创建查询参数对象
                    FeatureQueryResult features = await sFeatureLayer[i].FeatureTable.QueryFeaturesAsync(qParams); //在表上进行查询
                    List<Geometry> geometries = new List<Geometry>();
                    List<double> vs = new List<double>();
                    foreach (Feature f in features)
                    {
                        geometries.Add(f.Geometry);
                        vs.Add(Convert.ToDouble(sDistance[i]));
                    }
                    Geometry result = GeometryEngine.Buffer(geometries,vs,true).First();
                    union.Add(result);

                    Graphic g = new Graphic(result, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 250, 250, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));
                    _siteGraphicsOverlay.Graphics.Add(g);
                }
                else
                {
                    QueryParameters qParams = new QueryParameters();//创建查询参数对象
                    FeatureQueryResult features = await sFeatureLayer[i].FeatureTable.QueryFeaturesAsync(qParams); //在表上进行查询
                    List<Geometry> geometries = new List<Geometry>();
                    List<double> vs = new List<double>();
                    foreach (Feature f in features)
                    {
                        geometries.Add(f.Geometry);
                        vs.Add(Convert.ToDouble(sDistance[i]));
                    }
                    Geometry result = GeometryEngine.Buffer(geometries, vs, true).First();
                    cut.Add(result);

                    Graphic g = new Graphic(result, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 0, 250, 250), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));
                    _siteGraphicsOverlay.Graphics.Add(g);
                }
            }
            Geometry geometry1=null;
            Geometry geometry2;
            if (union.Count > 0)
            {
                if (union.Count == 1)
                {
                    geometry1 = union.First();
                }
                else
                {
                    geometry1 = union[0];
                    for (int k = 0; k < union.Count - 1; k++)
                    {
                        geometry1 = GeometryEngine.Intersection(GeometryEngine.Project(geometry1, MyMapView.SpatialReference), GeometryEngine.Project(union[k + 1], MyMapView.SpatialReference));
                        if (geometry1.IsEmpty)
                        {
                            MessageBox.Show("不存在所设条件的位置，请重新设置条件");
                            return;
                        }
                    }
                }
            }
            if (cut.Count>0 && union.Count > 0) {
                if (union.Count == 1)
                {
                    geometry2 = cut.First();
                }
                else
                {
                    geometry2 = GeometryEngine.Union(cut);
                }

                Geometry res = GeometryEngine.Difference(GeometryEngine.Project(geometry1, MyMapView.SpatialReference), GeometryEngine.Project(geometry2, MyMapView.SpatialReference));
                if (res.IsEmpty)
                {
                    MessageBox.Show("不存在所设条件的位置，请重新设置条件", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                Graphic r = new Graphic(res, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(200, 0, 250, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));
                _siteGraphicsOverlay.Graphics.Add(r);

                // 关闭
                Close();
            }
            else
            {
                Graphic r = new Graphic(geometry1, new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(200, 0, 250, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));
                _siteGraphicsOverlay.Graphics.Add(r);

                // 关闭
                Close();
            }
        }
    }


}
